<?php
if(!isset($_SESSION)) session_start();
if (isset($_SESSION['f_user_id'])) {
?><div id="fUserAccountBoxWrap">
	<div id="fUserAccountBox">
		<?php
			$user = $this->users()->user($_SESSION['f_user_id']);
			if ($user === null) {
				// TODO: better error handling
				echo 'Internal Error!';
			} else {
				$greeting = trim(t('Hello {first_name} {last_name}'));
				if ($greeting != '') {
					$greeting = str_replace('{first_name}',$user->first_name,$greeting);
					$greeting = str_replace('{last_name}',$user->last_name,$greeting);
					echo '<span class="f-user-greeting">'.$greeting.'</span>';
				}
				$form = $this->users()->user_form('logout');
				if ($form->submitted()) {
					unset($_SESSION['f_user_id']);
					$this->redirect($this->request);
				} else {				
					$form->render();
				}
			}
		?>
	</div>
</div><?php } else {
?><div id="fUserLoginBoxWrap">
	<div id="fUserLoginBox">
		<?php
			$form = $this->users()->user_form('login');
			if ($form->submitted()) {
				$form->load();
				$user = $this->users()->user($form->value('id'));
				if ($user != null && $user->check_password($form->value('password1'))) {
					$_SESSION['f_user_id'] = $user->id;
					$this->redirect($this->request);
				} else {
					$form->messages['f_user_form_login'] = t('Wrong login or password'); 
					$form->render();
				}
			} else {
				$form->render();
			}			
		?>
	</div>
</div><?php } ?>